package com.gvsoft.thread;

import com.gvsoft.Client;
import com.gvsoft.GVClientMThread;
import com.gvsoft.analyse.order.ClientKeepOrder;
import com.gvsoft.log.Logs;
import org.apache.commons.lang3.StringUtils;

import java.io.IOException;
import java.util.concurrent.ConcurrentHashMap;
import java.util.Map;

/**
 * Created with IntelliJ IDEA.
 * ProjectName:gvMsgClient
 * Author: zhaoqiubo
 * Date: 15/8/8
 * Time: 上午10:49
 * Desc: 维持链路线程，当获得服务端分配的令牌后启动。
 * 如果链路维护收不到服务端的响应一定次数后，则触发客户端对服务端的重连。
 */
public class KeepChannelThread extends Thread {


    public void run(){
        while(true){

            //构建链路维护指令对象
            ClientKeepOrder keepOrder = (ClientKeepOrder)Client.getOrderInstance(ClientKeepOrder.HEADER);
            keepOrder.initClientKeepOrder();
            if (StringUtils.isBlank(keepOrder.getToken())){
                Logs.info("【KeepChannelThread】","未收到服务端分配的身份标识，暂不发送链路维护报文！");
            }else {
                try {
                    //触发重连机制
                    if (Client.KEEP_ORDER_MAP.size()>=Client.getKeepTimeoutCount()){
                        Client.clearToken4Disconnect();
                        continue;
                    }
                    //发送链路维持报文
                    Client.write2Channel(keepOrder);
                    //保存链路维持报文到缓冲区，等待服务端回应清除。
                    ClientKeepOrder keepOrderValue = new ClientKeepOrder();
                    keepOrderValue = keepOrder;
                    Client.KEEP_ORDER_MAP.put(keepOrder.getRid(), keepOrderValue);
                } catch (IOException e) {
                    e.printStackTrace();
                    continue;
                }
            }
            try {
                Thread.sleep(Client.getKeepAliveCycle()*1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}
